import BatchOperation from "@/components/BatchOperation";
import PermissionControl from '@/components/PermissionControl';
import { batchRequestReview, requestReview, stockRequestList, stockRequestListDownload } from "@/services/stock-goods/subApi";
import { formatDate, isSupportSticky, showMsg } from "@/utils/utils";
import { PlusOutlined } from '@ant-design/icons';
import { ProFormDateRangePicker, ProFormText, ProFormTextArea } from "@ant-design/pro-form";
import ProTable, { ActionType, ProColumns } from "@ant-design/pro-table";
import { Button, Form, FormInstance, Popconfirm } from "antd";
import { MouseEvent, useRef, useState } from "react";
import { history, useModel } from "umi";
import './requestTab.less';

const RequestTab = (props: RequestTab) => {

  const { tab, brandList, classList, goodsList } = props;

  const { initialState } = useModel('@@initialState');
  const dept_level = initialState?.currentUser?.dept_level;

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const remarkRef = useRef<FormInstance>(null);
  const [batch, setBatch] = useState<boolean>();
  const [remarkType, setRemarkType] = useState<'N' | 'D'>('N');
  const [confirmOpen, setConfirmOpen] = useState<boolean>(false);
  const [confirmOffset, setConfirmOffset] = useState<number[]>([0, 0]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [enableDownload, setEnableDownload] = useState<boolean>(true);

  const columns: ProColumns<STOCKGOODSAPI.StockItem>[] = [
    {
      title: '申请部门',
      dataIndex: 'create_dept_name',
      hideInTable: dept_level === '2',
      hideInSearch: dept_level === '2',
      width: 100
    },
    {
      title: '批次号',
      dataIndex: 'batch_id',
      search: false,
      width: 100
    },
    {
      title: '操作类型',
      dataIndex: 'oper_type',
      search: false,
      valueEnum: {
        'I': '商品入库',
        'D': '库存调整',
        'R': '库存退回',
        'B': '库存批量调整'
      },
      width: 70
    },
    {
      title: '申请数量',
      dataIndex: 'inventory',
      search: false,
      width: 70
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        'W': '待审核',
        'N': '审核通过',
        'D': '审核拒绝'
      },
      formItemProps: {
        labelCol: { flex: '0 0 80px' }
      },
      width: 70
    },
    {
      title: '商品分类',
      dataIndex: 'class_id',
      hideInTable: true,
      order: 5,
      valueType: 'select',
      formItemProps: {
        labelCol: { flex: '0 0 80px' }
      },
      fieldProps: {
        placeholder: '选择商品分类',
        options: classList,
        showSearch: true
      }
    },
    {
      title: '商品品牌',
      dataIndex: 'brand_id',
      renderText: (_, r) => r.brand_name,
      order: 4,
      valueType: 'select',
      fieldProps: {
        placeholder: '选择商品品牌',
        options: brandList,
        showSearch: true
      },
      width: 100
    },
    {
      title: '商品名称',
      dataIndex: 'goods_id',
      renderText: (_, r) => r.goods_name,
      order: 3,
      valueType: 'select',
      fieldProps: form => ({
        options: goodsList,
        showSearch: true
      }),
      width: 100
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      search: false,
      width: 80
    },
    {
      title: '规格编号',
      dataIndex: 'specs_no',
      search: false,
      width: 80
    },
    {
      title: '规格描述',
      dataIndex: 'specs_name',
      ellipsis: true,
      search: false,
      width: 110
    },
    {
      title: '申请时间',
      dataIndex: 'submit_time',
      renderFormItem: ({ dataIndex }) => (
        <ProFormDateRangePicker
          name={dataIndex}
          placeholder={undefined}
          fieldProps={{ allowEmpty: [true, true], picker: 'date' }}
          wrapperCol={{ flex: '0 0 calc(100% + 6px)', style: { maxWidth: 'unset' } }}
        />
      ),
      width: 120
    },
    {
      title: '提交人',
      dataIndex: 'submit_user_name',
      search: false,
      width: 80
    },
    {
      title: '提交说明',
      dataIndex: 'submit_explain',
      search: false,
      width: 100
    },
    {
      title: '审批时间',
      dataIndex: 'approve_time',
      search: false,
      width: 120
    },
    {
      title: '审批人',
      dataIndex: 'approve_user_name',
      search: false,
      width: 80
    },
    {
      title: '审批说明',
      dataIndex: 'approve_explain',
      search: false,
      width: 100
    },
    dept_level === '2' ? { hideInTable: true, search: false } : {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (_, record) => (record.status !== 'W' ? [] : [
        <PermissionControl key="agree" action_id="200203011">
          <a onClick={e => initPopConfirm(e, 'N', false, record.approval_id)}>审批通过</a>
        </PermissionControl>
        ,
        <PermissionControl key="reject" action_id="200203012">
          <a onClick={e => initPopConfirm(e, 'D', false, record.approval_id)}>审批拒绝</a>
        </PermissionControl>
      ]),
      fixed: isSupportSticky() ? 'right' : false,
      width: 120
    }
  ];

  const initPopConfirm = (e: MouseEvent, type: 'N' | 'D', batch: boolean, rowId?: string) => {
    const { x, y } = e.currentTarget.getBoundingClientRect();
    setConfirmOffset([x - 136, y - 80]);
    setRemarkType(type);
    setBatch(batch);
    remarkRef.current?.resetFields();
    if (rowId) {
      if (remarkRef.current) {
        remarkRef.current?.setFieldsValue({ 'rowId': rowId });
      } else {
        setTimeout(() => remarkRef.current?.setFieldsValue({ 'rowId': rowId }), 10);
      }
    }
    setConfirmOpen(true);
  };

  /**
   * 审核
   */
  const review = () => {
    const remark = remarkRef.current?.getFieldValue('remark');
    if (!remark) {
      showMsg(`请填写${remarkType === 'N' ? '说明' : '拒绝原因'}`);
      return;
    }
    let req: Promise<any>;
    setLoading(true);
    if (batch === true) {
      if (selectedRowKeys.length == 0) {
        showMsg('请勾选需批量操作的行');
        setLoading(false);
        return;
      }
      req = batchRequestReview({ status: remarkType, ids: selectedRowKeys, remark });
    } else {
      const id = remarkRef.current?.getFieldValue('rowId');
      req = requestReview({ status: remarkType, id, remark }, remarkType === 'N' ? '200203011' : '200203012');
    }
    req.catch(res => {
      showMsg(res?.data?.errmsg);
    }).finally(() => {
      setConfirmOpen(false);
      setLoading(false);
      actionRef.current?.reload();
    });
  };

  /**
   * 下载
   */
  const onDownload = async () => {
    const { submit_time, ...params } = formRef.current?.getFieldsValue();
    if (submit_time) {
      params.begin_date = submit_time[0]?.format('YYYYMMDD');
      params.end_date = submit_time[1]?.format('YYYYMMDD');
    }
    setLoading(true);
    stockRequestListDownload(params, dept_level === '2' ? '200204004' : '200203009').then(res => {
      window.open(`/api/report/${res.file_token}/down`);
    }).finally(() => {
      setLoading(false);
    });
  };

  return <>
    {
      dept_level === '1' &&
      <Popconfirm
        icon={false}
        visible={confirmOpen}
        placement="topRight"
        align={{ offset: confirmOffset }}
        overlayClassName="popconfirmTitle"
        title={(
          <Form ref={remarkRef} onFinish={review}>
            <ProFormTextArea
              name="remark"
              label={remarkType === 'N' ? '说明' : '拒绝原因'}
              formItemProps={{ style: { marginBottom: 0 } }}
              fieldProps={{ autoSize: { minRows: 3, maxRows: 3 } }}
              rules={[{ required: true, message: '' }]}
            />
            <ProFormText name="rowId" hidden />
          </Form>
        )}
        onConfirm={() => remarkRef.current?.submit()}
        onCancel={() => setConfirmOpen(false)}>
      </Popconfirm>
    }
    <ProTable<STOCKGOODSAPI.StockItem>
      rowKey="approval_id"
      className="mytable"
      columns={columns}
      actionRef={actionRef}
      formRef={formRef}
      options={false}
      bordered
      loading={loading}
      search={{
        span: dept_level === '2' ? 8 : 6,
        labelWidth: 64,
        collapsed: false,
        collapseRender: false,
        optionRender: (_, __, [, query]) => ([
          query,
          <PermissionControl key="download" action_id="200203009,200204004">
            <Button type="primary" onClick={onDownload} disabled={!enableDownload}>下载</Button>
          </PermissionControl>
        ])
      }}
      beforeSearchSubmit={({ submit_time, ...params }) => {
        if (submit_time) {
          params.begin_date = submit_time[0] && formatDate(submit_time[0], 'YYYYMMDD');
          params.end_date = submit_time[1] && formatDate(submit_time[1], 'YYYYMMDD');
        }
        return params;
      }}
      request={async (params) => {
        setLoading(true);
        try {
          const res = await stockRequestList({ ...params }, dept_level === '2' ? '200204003' : '200203008');
          setEnableDownload(res.record_list && res.record_list.length !== 0);
          return {
            success: true,
            data: res.record_list,
            total: res.sum_record_num
          };
        } catch (reason) {
          return { success: false, data: [] };
        } finally {
          setLoading(false);
        }
      }}
      toolBarRender={() => [
        <>
          {
            dept_level === '2' &&
            <Button key="apply" type="primary" icon={<PlusOutlined />} onClick={() => history.push('/stock-goods/stock/request', { tab })}>
              库存申请
            </Button>
          }
          {
            dept_level === '1' &&
            <PermissionControl action_id="200203010">
              <BatchOperation options={[
                { value: 'N', label: '审批通过', confirm: false, onOk: async (_, e: any) => initPopConfirm(e, 'N', true) },
                { value: 'D', label: '审批拒绝', confirm: false, onOk: async (_, e: any) => initPopConfirm(e, 'D', true) }
              ]} />
            </PermissionControl>
          }
        </>
      ]}
      pagination={{ showQuickJumper: true }}
      rowSelection={dept_level === '2' ? false : {
        type: "checkbox",
        columnWidth: 40,
        fixed: isSupportSticky() ? true : false,
        onChange: selectedRowKeys => setSelectedRowKeys(selectedRowKeys),
        getCheckboxProps: ({ status }) => ({ disabled: status !== 'W' })
      }}
      scroll={{ scrollToFirstRowOnChange: true, x: 1000 }}
    />
  </>;
};

export default RequestTab;

interface RequestTab {
  tab: string
  classList: COMMON.SelectOption[]
  brandList: COMMON.SelectOption[]
  goodsList: COMMON.SelectOption[]
}
